package java8;

import java.util.Arrays;
import java.util.List;
import java.util.StringJoiner;

public class StringJoinerSample {

    public static void main(String[] args) {
        // =================================
        // StringJoiner 字符串拼接
        // =================================
        // 元素之间用指定的分隔符分隔
        StringJoiner joiner = new StringJoiner(",")
                .add("Annie")
                .add("Cindy")
                .add("Jason");
        // ===> Annie,Cindy,Jason
        System.out.println(joiner.toString());
        // 计算字符串长度
        // ===> 17
        System.out.println(joiner.length());
        // 两个或以上的元素之间才会使用分隔符
        joiner = new StringJoiner(",")
                .add("Annie");
        // ===> Annie
        System.out.println(joiner.toString());
        // 字符串用指定的前缀字符和后缀字符包裹, 元素之间用指定的分隔符分隔
        joiner = new StringJoiner(",", "[", "]")
                .add("Annie")
                .add("Cindy")
                .add("Jason");
        // ===> [Annie,Cindy,Jason]
        System.out.println(joiner.toString());
        // setEmptyValue: 仅当没有调用过add方法, StringJoiner为空时, 返回setEmptyValue设置的值
        StringJoiner strJoiner = new StringJoiner(",");
        strJoiner.setEmptyValue("Empty-Value");
        // ===> Empty-Value
        System.out.println(strJoiner.toString());

        // merge: 合并, 将另一个StringJoiner的元素(不带前缀和后缀及分隔符)添加到当前的StringJoiner中
        StringJoiner j1 = new StringJoiner(",")
                .add("Annie")
                .add("Cindy");
        StringJoiner j2 = new StringJoiner(",", "[", "]")
                .add("Jason")
                .add("Kelly");
        // j1 合并 j2
        j1.merge(j2);
        // ===> Annie,Cindy,Jason,Kelly
        System.out.println(j1.toString());
        // j2 合并 j1
        j2.merge(j1);
        // ===> [Jason,Kelly,Annie,Cindy]
        System.out.println(j2.toString());

        // =================================
        // String 字符串拼接
        // =================================
        String str1 = String.join(",", "Annie", "Cindy", "Jason");
        // ===> Annie,Cindy,Jason
        System.out.println(str1);
        List<String> list = Arrays.asList("Annie", "Cindy", "Jason");
        String str2 = String.join(",", list);
        // ===> Annie,Cindy,Jason
        System.out.println(str2);
    }

}